<template>
  <div class="dish-manage">
    <!-- 搜索和操作区 -->
    <div class="operation-area">
      <!-- 添加搜索和分类筛选 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item>
          <el-input
            v-model="searchForm.name"
            placeholder="请输入菜品名称"
            clearable
            @clear="handleSearch">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-select 
            v-model="searchForm.categoryId" 
            placeholder="请选择分类"
            clearable
            @clear="handleSearch">
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
        <el-button type="primary" @click="handleAdd">添加菜品</el-button>
      </el-form>
    </div>

    <!-- 菜品列表 -->
    <el-table :data="dishList" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="name" label="菜品名称"></el-table-column>
      
      <el-table-column prop="price" label="价格">
        <template slot-scope="scope">
          ¥{{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column prop="categoryName" label="分类"></el-table-column>
      <el-table-column prop="description" label="描述" show-overflow-tooltip></el-table-column>
      <el-table-column label="状态" width="100">
        <!-- eslint-disable-next-line vue/no-unused-vars -->
        <template slot-scope="scope">
          <el-tag type="success">上架</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="10"
        layout="total, prev, pager, next"
        :total="total">
      </el-pagination>
    </div>

    <!-- 添加/编辑菜品对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="dishForm" :rules="rules" ref="dishForm" label-width="100px">
        <el-form-item label="菜品名称" prop="name">
          <el-input v-model="dishForm.name"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="dishForm.price" :min="0" :precision="2"></el-input-number>
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="dishForm.categoryId" placeholder="请选择分类">
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="dishForm.description"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getDishList, addDish, deleteDish, updateDish } from '@/api/dish'
import { getCategory } from '@/api/category'

export default {
  name: 'DishManage',
  data() {
    return {
      dishList: [],
      currentPage: 1,
      total: 0,
      dialogVisible: false,
      dialogTitle: '添加菜品',
      categories: [],
      dishForm: {
        name: '',
        price: 0,
        categoryId: '',
        description: '',
        status: 1,
        createdAt: '',
        updatedAt: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入菜品名称', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入价格', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ]
      },
      uploadHeaders: {
        'Authorization': localStorage.getItem('token') || ''
      },
      searchForm: {
        name: '',
        categoryId: ''
      }
    }
  },
  created() {
    this.fetchDishList()
    this.fetchCategories()
  },
  methods: {
    // 获取菜品列表
    async fetchDishList() {
      try {
        const res = await getDishList({
          page: this.currentPage || 1,
          name: this.searchForm.name,
          categoryId: this.searchForm.categoryId
        })
        if(res.data) {
          this.dishList = res.data.records || []
          this.total = res.data.total || 0
        }
      } catch (error) {
        this.$message.error('获取菜品列表失败')
        this.dishList = []
        this.total = 0
      }
    },
    // 获取分类列表
    async fetchCategories() {
      try {
        const res = await getCategory('', 1)
        this.categories = res.data.records
      } catch (error) {
        this.$message.error('获取分类列表失败')
      }
    },
    // 处理页码改变
    handleCurrentChange(page) {
      this.currentPage = page || 1
      this.fetchDishList()
    },
    // 处理添加按钮点击
    handleAdd() {
      this.dialogTitle = '添加菜品'
      this.dishForm = {
        name: '',
        price: 0,
        categoryId: '',
        description: '',
        status: 1,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      }
      this.dialogVisible = true
    },
    // 处理删除
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该菜品吗？', '提示', {
          type: 'warning'
        })
        await deleteDish(row.id)
        this.$message.success('删除成功')
        this.fetchDishList()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },
    // 提交表单
    async submitForm() {
      this.$refs.dishForm.validate(async (valid) => {
        if (valid) {
          try {
            const api = this.dishForm.id ? updateDish : addDish
            await api(this.dishForm)
            this.$message.success(this.dishForm.id ? '修改成功' : '添加成功')
            this.dialogVisible = false
            this.fetchDishList()
          } catch (error) {
            this.$message.error(this.dishForm.id ? '修改失败' : '添加失败')
          }
        }
      })
    },
    // 处理编辑
    handleEdit(row) {
      this.dialogTitle = '编辑菜品'
      this.dishForm = { 
        ...row,
        updatedAt: new Date().toISOString()
      }
      this.dialogVisible = true
    },
    // 添加搜索处理方法
    handleSearch() {
      this.currentPage = 1
      this.fetchDishList()
    }
  }
}
</script>

<style scoped>
.dish-manage {
  padding: 20px;
}
.operation-area {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.search-form {
  display: flex;
  align-items: center;
}
.search-form .el-form-item {
  margin-bottom: 0;
  margin-right: 10px;
}
</style>
